﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Browser;

using System.Windows.Media;
using System.Windows.Documents;

namespace SampleBrowser.Util
{
    /// <summary>
    /// Represents a font resource in an assembly.
    /// </summary>
    public class FontResourceInfo
    {
        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name { get; private set; }
        /// <summary>
        /// Gets or sets the font URI.
        /// </summary>
        /// <value>The font URI.</value>
        public Uri FontUri { get; private set; }
        /// <summary>
        /// Gets the font stream.
        /// </summary>
        /// <value>The font stream.</value>
        public Stream FontStream
        {
            get
            {
                var streamInfo = Application.GetResourceStream(this.FontUri);
                return streamInfo.Stream;
            }
        }
        
        /// <summary>
        /// Retrieves information for all fonts available as resource in specified assembly.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <returns></returns>
        public static IEnumerable<FontResourceInfo> AllFonts(Assembly assembly)
        {
            if (assembly == null) {
                throw new ArgumentNullException("assembly");
            }

            IEnumerable<string> resourceNames;

            // find all resources in this assembly
            var streamName = (from name in assembly.GetManifestResourceNames()
                                where name.EndsWith(".g.resources")
                                select name).FirstOrDefault();

            if (streamName == null) {
                yield break;
            }

            using (var stream = assembly.GetManifestResourceStream(streamName)) {
                var reader = new ResourceReader();
                resourceNames = from name in reader.GetResourceNames(stream)
                                orderby name
                                select name;

                foreach (var name in resourceNames) {
                    var extension = Path.GetExtension(name).ToLowerInvariant();
                    if (extension == ".otf" || extension == ".ttf") {
                        yield return new FontResourceInfo() {
                            Name = HttpUtility.UrlDecode(Path.GetFileName(name)),
                            FontUri = new Uri(string.Format("/SampleBrowser;component/{0}", name), UriKind.Relative)
                        };
                    }
                }
            }
        }
    }
}
